package com.yugao.fintech.antelope.infra.module.dict;

import com.yugao.fintech.antelope.infra.module.dict.model.entity.DictItem;
import com.yugao.fintech.framework.assistant.utils.reflection.MetaObject;
import com.yugao.fintech.framework.desensitization.fieldbind.inter.IDataBind;
import com.yugao.fintech.framework.desensitization.fieldbind.model.DictType;
import com.yugao.fintech.framework.desensitization.fieldbind.model.FieldBindAnnotationData;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 数据库字段字典绑定

 */
@Component
public class DictFieldBind implements IDataBind<Map<String, Map<String, DictItem>>> {
    private static final Map<String, DictItem> EMPTY_MAP = new HashMap<>();
    @Autowired
    private DictItemApi dictItemApi;

    @Override
    public Map<String, Map<String, DictItem>> getCodesOfTypes(List<DictType> dictTypes) {
        return dictItemApi.listByCodes(dictTypes.stream().map(DictType::getType).collect(Collectors.toList()));
    }

    @Override
    public void setMetaObject(MetaObject metaObject, Map<String, Map<String, DictItem>> codesOfTypes,
                              Object fieldValue, FieldBindAnnotationData annotationData) {
        // 通过type或者对应的字典键值对, 然后通过 fieldValue = itemLabel, 或者对应的 itemValue
        Object value = this.assemblyTargetFieldValue(fieldValue, annotationData, code -> {
            DictItem data = Optional.ofNullable(codesOfTypes.get(String.valueOf(annotationData.getType())))
                    .orElse(EMPTY_MAP).get(String.valueOf(code));
            return Optional.ofNullable(data).map(DictItem::getItemLabel).orElse("");
        });
        metaObject.setValue(annotationData.getTarget(), value);
    }
}
